#include <fhegraphics/GLWidget.h>
#include <fhe/core/Util.h>
#include <GL/glu.h>

namespace fhe
{
  namespace graphics
  {
    GLWidget::GLWidget( QWidget* parent, Color clearColor, RenderTarget* renderTarget )
      : Super( parent )
      , clearColor_( clearColor )
      , renderTarget_( renderTarget )
    {
      FHE_ASSERT( renderTarget_ );
    }
    
    GLWidget::~GLWidget()
    {
    }
    
    void GLWidget::initializeGL()
    {
      glEnable( GL_TEXTURE_2D );
      glShadeModel( GL_SMOOTH );
      glEnable( GL_BLEND );
      glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
      glLineWidth( 2 );
      glClearColor( clearColor_.r, clearColor_.g, clearColor_.b, clearColor_.a );
      glEnable( GL_DEPTH_TEST );
      glEnable( GL_NORMALIZE );
      glColor4d( 1., 1., 1., 1. );
      glBindTexture( GL_TEXTURE_2D, 0 );
      glBindTexture( GL_TEXTURE_3D, 0 );
    }
    
    void GLWidget::resizeGL( int w, int h )
    {
      glMatrixMode( GL_PROJECTION );
      glLoadIdentity();
      gluPerspective( 45, double( w ) / double( h ), 1, 1000 );
    }
    
    void GLWidget::paintGL()
    {
      glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
      glMatrixMode( GL_MODELVIEW );
      glLoadIdentity();
      renderTarget_->render();
      glFlush();
    }
  }
}
